let http = require('http');

interface stringResult
{
    success: boolean
    message: string
    content: string
}

/**
 * 以Get 方法获取 http 消息
 * 本方法总是以 resolve 的形式返回 stringResult
 * 使用时需要 await
 * @param theUrl 需要访问的链接
 */
async function _getStringViaHTTP(theUrl: string): Promise<stringResult>
{
    return new Promise(function (resolve)
    {
        let r: stringResult = {
            success: false,
            message: "未捕获到错误",
            content: ""
        }
        http.get(theUrl, (res) =>
        {
            const {statusCode} = res;
            let error;
            if (statusCode !== 200)
            {
                error = new Error(`请求失败. Status Code: ${statusCode}`);
            }
            if (error)
            {
                console.error(error.message);
                // 释放内存
                res.resume();
                r.message = error.message;
                resolve(r);
                return;
            }

            res.setEncoding('utf8');
            let rawData = '';
            res.on('data', (chunk) =>
            {
                rawData += chunk;
            });
            res.on('end', () =>
            {
                r.success = true;
                r.content = rawData;
                resolve(r);
            });
        }).on('error', (e) =>
        {
            r.message = e.message;
            resolve(r);

        });
    })
}

export {stringResult, _getStringViaHTTP}

